package com.limedia.explorer.http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

public class HttpCookieStore implements CookieStore {
	
//	private static final String TAG = HttpCookieStore.class.getSimpleName();
	private static final String COOKIE_PREFS = "CookiePrefsFile";
	private static final String COOKIE_NAME_URI = "cookie_uri";
	private static final String COOKIE_NAME_STORE = "names";
	private static final String COOKIE_NAME_PREFIX = "cookie_";
	
	private final ConcurrentHashMap<String, HttpCookie> cookies;
    private final SharedPreferences cookiePrefs;
	private final List<String> storedCookieNames;
	
	private String storedUri = null;

	public HttpCookieStore (Context context, List<String> cookieNames) {
		super();
		
		if(null == cookieNames || cookieNames.isEmpty()) {
			throw new IllegalArgumentException("cookieNames is null!");
		}
		
		this.storedCookieNames = cookieNames;
		this.cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
		this.cookies = new ConcurrentHashMap<String, HttpCookie>();
		
		this.loadStoredCookies(false);
	}
	
	public HttpCookieStore(Context context) {
		super();
		
		this.storedCookieNames = new ArrayList<String>();
		this.cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
		this.cookies = new ConcurrentHashMap<String, HttpCookie>();
		
		this.loadStoredCookies(true);
	}
	
	@Override
	public void add(URI uri, HttpCookie cookie) {
		SharedPreferences.Editor preferEditor = this.cookiePrefs.edit();
		
		if(null == this.storedUri) {
			this.storedUri = uri.getHost();
			preferEditor.putString(COOKIE_NAME_URI, this.storedUri);
		} else if(!this.storedUri.equals(uri.getHost())) {
			this.storedUri = uri.getHost();
			preferEditor.putString(COOKIE_NAME_URI, this.storedUri);
			this.removeAll();
		}
		String name = this.getCookieToken(uri, cookie);
		// Save cookie into local store, or remove if expired
		if(!cookie.hasExpired()) {
			this.cookies.put(name, cookie);
		} else {
			this.cookies.remove(name);
		}
		// Save cookie into persistent store
		preferEditor.putString(COOKIE_NAME_STORE, TextUtils.join(",", this.cookies.keySet()));
		preferEditor.putString(COOKIE_NAME_PREFIX, this.encodeCookie(new HttpSerializableCookie(cookie)));
		preferEditor.commit();
	}

	@Override
	public List<HttpCookie> get(URI uri) {
		if(null != this.storedUri && this.storedUri.equals(uri.getHost())) {
			ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
			ret.addAll(this.cookies.values());
	        return ret;
        } else {
        	return null;
        }
	}

	@Override
	public List<HttpCookie> getCookies() {
		ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
        ret.addAll(cookies.values());
        return ret;
	}

	@Override
	public List<URI> getURIs() {
		ArrayList<URI> ret = new ArrayList<URI>();
		try {
			if(null != this.storedUri) {
				ret.add(new URI(this.storedUri));
			}
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
        return ret;
	}

	@Override
	public boolean remove(URI uri, HttpCookie cookie) {
		String name = getCookieToken(uri, cookie);
        if(null != this.storedUri && this.storedUri.equals(uri.getHost()) && this.cookies.containsKey(name)) {
            this.cookies.remove(name);
            SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
            if(cookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
                prefsWriter.remove(COOKIE_NAME_PREFIX + name);
            }
            prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.keySet()));
            prefsWriter.commit();
            return true;
        } else {
            return false;
        }
	}

	@Override
	public boolean removeAll() {
		SharedPreferences.Editor prefsWriter = this.cookiePrefs.edit();
        prefsWriter.clear();
        prefsWriter.commit();
        this.cookies.clear();
        return true;
	}
	
	private String getCookieToken(URI uri, HttpCookie cookie) {
        return cookie.getName() + cookie.getDomain();
    }
	
	private void loadStoredCookies(boolean isLoadingAllCookies) {
		// Load any previously stored cookies into the store
		this.storedUri = this.cookiePrefs.getString(COOKIE_NAME_URI, null);
		String storedCookieNames = this.cookiePrefs.getString(COOKIE_NAME_STORE, null);
		if(null != storedCookieNames) {
			String[] cookieNames = TextUtils.split(storedCookieNames, ",");
			for (String name : cookieNames) {
				if(!isLoadingAllCookies && !this.storedCookieNames.contains(name)) {
					continue;
				}
                String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
                if (encodedCookie != null) {
                    HttpCookie decodedCookie = decodeCookie(encodedCookie);
                    if (decodedCookie != null) {
                        cookies.put(name, decodedCookie);
                    }
                }
			}
		}
	}
	
	protected HttpCookie decodeCookie(String cookieString) {
        byte[] bytes = hexStringToByteArray(cookieString);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        HttpCookie cookie = null;
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            cookie = ((HttpSerializableCookie) objectInputStream.readObject()).getCookie();
        } catch (IOException e) {
        	e.printStackTrace();
        } catch (ClassNotFoundException e) {
        	e.printStackTrace();
        }
        return cookie;
	}
	
	/**
     * Serializes Cookie object into String
     *
     * @param cookie cookie to be encoded, can be null
     * @return cookie encoded as String
     */
    protected String encodeCookie(HttpSerializableCookie cookie) {
        if (cookie == null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(os);
            outputStream.writeObject(cookie);
        } catch (IOException e) {
        	e.printStackTrace();
            return null;
        }

        return byteArrayToHexString(os.toByteArray());
    }
	
	protected String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        for (byte element : bytes) {
            int v = element & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        return sb.toString().toUpperCase(Locale.US);
    }
	
    protected byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }
}
